package com.sjs.boot.dynamic.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @author uto_dev_008
 * @desc
 * @since 2021/11/30 13:56
 * Copyright (c) 2021 南京友拓信息技术有限公司 All rights reserved
 */
public class FileUtil {
    private static final Logger LOG = LoggerFactory.getLogger(FileUtil.class);
    private static final int BUFF_SIZE = 1024 * 4;

    public static final byte[] readStream(InputStream in) {
        int readLen;
        byte[] content = new byte[BUFF_SIZE];
        ByteArrayOutputStream bos = new ByteArrayOutputStream(BUFF_SIZE * 2);
        try {
            while ((readLen = in.read(content)) > 0) {
                bos.write(content, 0, readLen);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            LOG.error("Fail to read stream", e);
        } finally {
            closeQuietly(bos);
        }

        return null;
    }

    public static final byte[] readFile(File file) {
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            byte[] bytes = new byte[in.available()];
            in.read(bytes);
            return bytes;
        } catch (FileNotFoundException e) {
            LOG.error("File not found {}", file, e);
        } catch (IOException e) {
            LOG.error("Fail to read {}", file, e);
        } finally {
            closeQuietly(in);
        }
        return null;
    }


    public static final void closeQuietly(OutputStream out) {
        if (out == null) {
            return;
        }

        try {
            out.close();
        } catch (IOException e) {
            LOG.error("Fail to close output stream, {}", e.toString());
        }
    }

    public static final void closeQuietly(InputStream in) {
        if (in == null) {
            return;
        }

        try {
            in.close();
        } catch (IOException e) {
            LOG.error("Fail to close input stream, {}", e.toString());
        }
    }
}
